<title>机构管理</title>

<div class="layui-fluid">
  <div class="layui-card">
    <form class="layui-form layui-card-header layuiadmin-card-header-auto" lay-filter="LAY_org_form" id='LAY_org_form_view'></form>
    <script type="text/html" id="LAY_org_form_tpl">
      <div class="layui-form-item">
        {{# if (d.category == "ORG") { }}
        <div class="layui-inline">
          <label class="layui-form-label">机构类型</label>
          <div class="layui-input-block">
            <select name="orgCategory">
              <option value="">请选择</option>
              <option value="ORG">总公司</option>
              <option value="BROKER_ORG">经纪公司</option>
              <option value="TEAM">代理人团队</option>
              <option value="CHANNEL">渠道</option>
              <option value="CHANNEL_SUB_ACC">渠道子账户</option>
            </select>
          </div>
        </div>
        {{# } }}

        <div class="layui-inline">
          <label class="layui-form-label">机构名称</label>
          <div class="layui-input-block">
            <input type="text" name="orgName" placeholder="请输入" autocomplete="off" class="layui-input">
          </div>
        </div>

        <div class="layui-inline">
          <button class="layui-btn layuiadmin-btn-useradmin" lay-submit lay-filter="LAY_org_form_search">
            <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i> 查询
          </button>
          <button type="reset" class="layui-btn layuiadmin-btn-useradmin">
            <i class="layui-icon layui-icon-refresh layuiadmin-button-btn"></i> 重置
          </button>
          {{# if (d.category == "ORG") { }}
            <button type="button" class="layui-btn layuiadmin-btn-useradmin LAY_btn_channel_audit" lay-href="/organization/audit">
            <i class="layui-icon layui-icon-survey layuiadmin-button-btn"></i> 渠道审核
          </button>
          {{# } }}
          {{# if (d.category == "ORG" || d.category == "CHANNEL") { }}
          <button type="button" class="layui-btn layuiadmin-btn-useradmin LAY_org_add">
            <i class="layui-icon layui-icon-addition layuiadmin-button-btn"></i> 新增机构
          </button>
          {{# } }}
        </div>
      </div>
    </script>

    <div class="layui-card-body">
        <table id="LAY_org" lay-filter="LAY_org"></table>
        <script type="text/html" id="LAY_org_toolbar" lay-filter="LAY_org_toolbar">
          {{# if (d.showPolicySetBtn) { }}
            <a class="layui-btn layui-btn-xs LAY_btn_list_set" lay-event="set">政策设置</a>
          {{# } }}
          {{# if (d.showEnableBtn) { }}
          <a class="layui-btn layui-btn-xs LAY_btn_list_enable" lay-event="enable">启用</a>
          {{# } }}
          {{# if (d.showDisableBtn) { }}
          <a class="layui-btn layui-btn-xs layui-btn-danger LAY_btn_list_disable" lay-event="disable">禁用</a>
          {{# } }}
          {{# if (d.showUpdateBtn) { }}
          <a class="layui-btn layui-btn-xs LAY_btn_list_modify" lay-event="modify">修改</a>
          {{# } }}
          {{# if (d.showResetPwdBtn) { }}
          <a class="layui-btn layui-btn-xs LAY_btn_list_reset" lay-event="reset">重置密码</a>
          {{# } }}
        </script>
    </div>
  </div>
</div>

<script type="text/html" id="LAY_password_form">
  <div class="layui-fluid">
    <form class="layui-form" lay-filter="LAY_password_form">
      <div class="layui-form-item">
        <label class="layui-form-label">新密码</label>
        <div class="layui-input-block">
          <input type="password" name="password" lay-verify="required|password" placeholder="请输入" autocomplete="off" class="layui-input">
        </div>
      </div>
      <button class="LAY_password_form_save" style="display: none;" lay-submit lay-filter="LAY_password_form_save">保存</button>
    </form>
  </div>
</script>

<script>
  layui.use(['admin', 'form', 'element', 'laypage', 'laytpl', 'table', 'md5', 'getmenus'], function () {
    var $ = layui.$,
    admin = layui.admin,
    setter = layui.setter,
    view = layui.view,
    table = layui.table,
    laytpl = layui.laytpl,
    laypage = layui.laypage,
    element = layui.element,
    form = layui.form,
    getmenus = layui.getmenus,
    params = {};

    var data = {
      category: sessionStorage.category
    };

    renderForm(data, function () {
      initForm();
      initOrgList();
      initEvents();
    });

    function initForm() {
      // 初始化表单
      form.render(null, 'LAY_org_form');
      initPermission();
      // 表单提交
      form.on('submit(LAY_org_form_search)', function (data) {
        var field = data.field;
        params = $.extend(true, params, field);

        reloadOrgList(params, 1);
        return false;
      });
    }
    function renderForm(data, callback) {
      var getTpl = $('#LAY_org_form_tpl').html();
      if (!getTpl) {
        return;
      }
      laytpl(getTpl).render(data, function(html){
        $('#LAY_org_form_view').html(html);

        if (typeof(callback) === 'function') {
          callback();
        }
      });
    }

    // 初始化table
    function initOrgList() {
      var field = form.val('LAY_org_form');
      params = $.extend(true, params, field);

      table.render({
        elem: '#LAY_org'
        ,where: params
        ,page: true
        ,url: setter.url + '/org/pageList' //模拟接口
        ,data: []
        ,cols: [[
          { field: 'orgSimpleName', align: 'center', title: '机构简称', templet: function (d) {
            if (d.orgCode == 'jhj') {
              return d.orgSimpleName;
            }
            return '<a class="LAY_url_a" lay-href="/organization/detail/orgCode='+ d.orgCode + '/showUpdateBtn=' + d.showUpdateBtn +'">' + d.orgSimpleName + '</a>';
          }}
          ,{ field: 'parentOrgSimpleName', align: 'center', title: '上级机构简称' }
          ,{ field: 'orgCategoryDesc', align: 'center', title: '机构类型' }
          ,{ field: 'orgCode', align: 'center', title: '机构编码' }
          ,{ field: 'merchantCode', align: 'center', title: '商户编码' }
          ,{ field: 'enableStatusDesc', align: 'center', title: '启用状态' }
          ,{ field: 'developModeDesc', align: 'center', title: '开发状态' }
          ,{ field: 'auditStatusDesc', align: 'center', title: '审核状态' }
          ,{ field: 'policySetDesc', align: 'center', title: '政策状态' }
          ,{ title: '操作', width: 300, align: 'center', fixed: 'right',  toolbar: '#LAY_org_toolbar' }
        ]]
        ,parseData: function(res){
          return {
            "code": res.code,
            "msg": res.msg,
            "data": res.data.list,
            "count": res.data.pageInfo.count,
          };
        }
        ,response: {
          statusCode: 200 //规定成功的状态码，默认：0
        } 
        ,request: {
          limitName: 'pageSize'
        }
        ,done: function () {
          initTablePermission();
        }
      });

      table.on('tool(LAY_org)', function(obj){
        var data = obj.data;

        switch (obj.event) {
          case 'set':
            setPolicy(data.orgCode);
            break;
          case 'enable':
            if (data.policySetDesc == '未设置') {
              layer.alert('请先为机构设定政策');
            } else {
              updataStatus(data.orgCode, 1);
            }
            break;
          case 'disable':
            updataStatus(data.orgCode, 0);
            break;
          case 'modify':
            layerShow(data.orgCode, 'modify');
            break;
          case 'reset':
            passwordLayerShow(data.orgCode);
            break;
          default:
            break;
        }
      });
    }

    // 设定政策
    function setPolicy(orgCode) {
      admin.req({
          url: setter.url + '/org/policySetPreconditionChk',
          type: 'GET',
          data: {
            targetOrgCode: orgCode,
          },
          done: function (res) {
            var data = res.data;
            if (data) {
              location.hash = '/organization/productList/orgCode=' + data.orgCode + '/orgName=' + data.orgName;
            }
          }
        });
    }

    // 修改密码
    function passwordLayerShow(orgCode) {
      var html = $('#LAY_password_form').html();

      layer.open({
        type: 1,
        title: '重置密码',
        area: ['600px'],
        content: html,
        btn: ['保存', '取消'],
        success: function (layero, index) {
          form.render(null, LAY_password_form);
          form.verify({
            password: function (value, item) {
              if (!/^(?!^[\d]+$)(?!^[_]+$)(?!^[a-zA-Z]+$)[\w-]{6,12}$/.test(value)) {
                return '6位-12位；至少同时包含字母、数字，下划线中的任意两种';
              }
            }
          });
          form.on('submit(LAY_password_form_save)', function (data) {
            var field = data.field;
            admin.req({
              url: setter.url + '/org/associatedPassportPasswordReset',
              type: 'POST',
              data: {
                orgCode: orgCode,
                password: md5(field.password)
              },
              done: function (res) {
                var data = res.data;

                var msg = '操作失败'
                var icon = 2;

                if (data) {
                  msg = '操作成功';
                  icon = 1;
                  layer.close(index);
                }

                layer.msg(msg, {
                  icon: icon,
                  time: 1500,
                  shade: [0.3, '#393D49']
                });
              }
            });
            return false;
          });
        },
        yes: function(index, layero){
          $('.LAY_password_form_save').click();
          return false;
        }
      });
    }

    // reload table
    function reloadOrgList(params, curr, callback) {
      table.reload('LAY_org', {
        where: params
        ,page: {
          curr: curr
        }
        ,done: function (res) {
          if (typeof(callback) == 'function') {
            callback(res);
          }
        }
      })
    }

    function initEvents() {
      $('.LAY_org_add').off('click').on('click', function () {
        layerShow();
      });
    }

    // 更新启用/禁用状态
    function updataStatus(orgCode, optCode) {
      layer.msg('更新中', {
        icon: 16,
        time: 1500,
        shade: [0.3, '#393D49']
      }, function(){
        admin.req({
          url: setter.url + '/org/enableOrDisable',
          type: 'POST',
          data: {
            orgCode: orgCode,
            optCode: optCode
          },
          done: function (res) {
            var data = res.data;

            var msg = '操作失败'
            var icon = 2;

            if (data) {
              msg = '操作成功';
              icon = 1;
            }

            layer.msg(msg, {
              icon: icon,
              time: 1500,
              shade: [0.3, '#393D49']
            });

            reloadOrgList(params);
          }
        });
      });
    }

    // 显示编辑页
    function layerShow(orgCode, status) {
      var index = layer.open({
        type: 2
        ,title: orgCode ? '修改机构' : '新增机构'
        ,area: ['80%', '700px']
        ,content: '#/organization/form/orgCode=' + orgCode + '/status=' + status
        ,btn: ['确定', '取消']
        ,yes: function(index, layero){
          var body = layer.getChildFrame('body', index);
          body.find('#LAY_org_form_submit').click();
          return false;
        }
      });
    }

    function initPermission() {
      // 渠道审核
      var auditBtn = $('.LAY_btn_channel_audit');
      if (!getmenus.orgAudit) {
        auditBtn.remove();
      }
      // 新增机构
      var addBtn = $('.LAY_org_add');
      if (!getmenus.orgAdd) {
        addBtn.remove();
      }
    }
    function initTablePermission() {
      // 设定政策
      var setBtn = $('.LAY_btn_list_set');
      if (!getmenus.orgEditPlans) {
        setBtn.remove();
      }
      // 重置密码
      var resetBtn = $('.LAY_btn_list_reset');
      if (!getmenus.orgPassReset) {
        resetBtn.remove();
      }
      // 修改机构
      var modifyBtn = $('.LAY_btn_list_modify');
      if (!getmenus.orgModify) {
        modifyBtn.remove();
      }

      // 启用禁用机构
      var enableBtn = $('.LAY_btn_list_enable');
      var disableBtn = $('.LAY_btn_list_disable');
      if (!getmenus.orgEnableOrDisable) {
        enableBtn.remove();
        disableBtn.remove();
      }
    }
    window.refresh = function () {
      reloadOrgList(params);
    };

  });
</script>